package com.atguigu.spzx.manager.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.spzx.manager.handler.CategoryExcelListener;
import com.atguigu.spzx.manager.mapper.CategoryMapper;
import com.atguigu.spzx.manager.service.CategoryService;
import com.atguigu.spzx.model.dto.product.CategoryExcelDTO;
import com.atguigu.spzx.model.entity.product.Category;
import com.atguigu.spzx.model.exception.SpzxException;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {
    @Resource
    CategoryMapper categoryMapper;
    @Override
    public List<Category> listByPid(Long pid) {
        List<Category> categories = categoryMapper.selectByPid(pid);
        //查询每个Category是否有下一级
        categories.forEach(category -> {
            Long count = categoryMapper.selectCountByPid(category.getId());
            category.setHasChildren(count>0);
        });
        return categories;
    }
//    @Resource
    @Override
    public void importCates(MultipartFile file) {
        if(file.isEmpty()){
            throw new SpzxException(ResultCodeEnum.FILE_UPLOAD_ERROR);
        }
        try {
            //使用EasyExcel解析文件
            EasyExcel.read(file.getInputStream())
                    .head(CategoryExcelDTO.class)
                    .registerReadListener(new CategoryExcelListener(categoryMapper))
                    .doReadAll();
        } catch (Exception e) {
            throw new SpzxException(ResultCodeEnum.FILE_UPLOAD_ERROR,e);
        }


    }

    @Override
    public void exportCates(HttpServletResponse response) {
        try {
            //==============1、检查用户是否有权限访问该文件
            //2、配置响应体内容的描述：告诉浏览器如何解析响应体中的文件
            String fileName = URLEncoder.encode("分类数据_"+new DateTime().toString("yyyy-MM-dd_HH") +".xlsx" , "UTF-8");
            response.setHeader("content-disposition" , "attachment;filename="+fileName);
            //3、查询要导出的数据
            List<CategoryExcelDTO> list = categoryMapper.selectAll();
            //4、使用easyexcel写入到excel文件中
            EasyExcel.write(response.getOutputStream())
                    .head(CategoryExcelDTO.class)
                    .sheet("分类数据")
                    .doWrite(list);
            //4、将文件流写入到response的响应体中
        } catch (Exception e) {
            throw new SpzxException(ResultCodeEnum.FILE_EXPORT_ERROR,e);
        }


    }
}
